package shopping.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shopping.demo.entities.Order;
import shopping.demo.exception.OrderException;
import shopping.demo.exception.order.OrderStatusOperationException;
import shopping.demo.util.OrderIdUtils;

@Service
public class OrderCommitService {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    private Logger logger = LoggerFactory.getLogger(OrderCommitService.class);
    //提交订单
    @Transactional
    public void commitOrder(Order order) throws Exception{
        //判断订单的状态（必须核对的是数据库中的信息）
        if(!OrderIdUtils.CREATED.equals(orderService.findById(order.getOid()).getStatus())) {
            throw new OrderStatusOperationException();
        }
        //提交订单
        orderService.changeStatus(order.getOid(),OrderIdUtils.COMMIT);
        //用户资金减少
        userService.moneyDown(order.getUid(),order.getPrice());
        //商品库存减少
        goodsService.countDown(order.getGid(),order.getCount());
        logger.info("订单【{}】提交成功",order.getOid());
    }
}
